package com.wandousoushu.jiusen.adapter;

import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.wandousoushu.jiusen.R;

public class SearchKeyAdapter extends RecyclerView.Adapter<SearchKeyAdapter.Vh>  {

    private Context mContext;
    private String[] mKeyList;
    private LayoutInflater mInflater;
    private ActionListener mActionListener;
    private View.OnClickListener mOnClickListener;

    public SearchKeyAdapter(Context mContext, String[] keyList) {
        this.mContext = mContext;
        this.mKeyList=keyList;
        mInflater = LayoutInflater.from(mContext);
        this.notifyDataSetChanged();
        mOnClickListener=new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Object tag = view.getTag();
                if(tag!=null){
                    int position = (int) tag;
                    if (mActionListener != null) {
                        mActionListener.onItemClick(mKeyList[position]);
                    }
                }
            }
        };
    }

    public void setActionListener(ActionListener listener) {
        mActionListener = listener;
    }

    @Override
    public SearchKeyAdapter.Vh onCreateViewHolder(ViewGroup parent, int viewType) {
        return new Vh(mInflater.inflate(R.layout.item_searck_key_text, parent, false));
    }

    @Override
    public void onBindViewHolder(SearchKeyAdapter.Vh holder, int position) {
        holder.setData(mKeyList[position], position);
    }

    @Override
    public int getItemCount() {
        return mKeyList.length;
    }

    class Vh extends RecyclerView.ViewHolder {
        TextView keyTextView;

        public Vh(View itemView) {
            super(itemView);
            keyTextView = (TextView) itemView.findViewById(R.id.text_key);
            itemView.setOnClickListener(mOnClickListener);
        }

        void setData(String key, int position) {
            itemView.setTag(position);
            keyTextView.setText(key);
        }
    }

    public interface ActionListener {
        void onItemClick(String key);
    }
}
